import cfg

import os
import subprocess
import time

MAX_DELTA=2*60
SLEEP_DURATION=5*60

def sch_should_restart():
	ts = time.localtime()
	t = time.mktime(ts)
	seconds = ts[3]*60*60 + ts[4]*60 + ts[5]
	midnight = t-seconds
	if abs(t-midnight)<MAX_DELTA:
		return False # no restart around midnight
	p = cfg.get_sch_log_path(create=False)
	if os.path.exists(p):
		s = os.stat(p)
		t_mod = s[8]
		t_delta =t-t_mod
		if t_delta>MAX_DELTA:
			return True
	else:
		return True
	return False

def main():
	print time.strftime("%Y-%m-%d %H:%M"),
	if sch_should_restart():
		print "starting SCH"
		os.chdir(cfg.src_root_dir)
		subprocess.Popen("start python sch.py",shell=True)
	else:
		print "SCH already running"

def mainloop():
	while True:
		main()
		time.sleep(SLEEP_DURATION)

if __name__=="__main__":
	mainloop()
